package org.meb.lotrlcg.web.ctrl;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;

import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;

import org.apache.commons.lang.StringUtils;
import org.meb.lotrlcg.web.services.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Named
@ViewScoped
public class LocaleCtrl implements Serializable {

	private static final Logger log = LoggerFactory.getLogger(LocaleCtrl.class);
	private static final long serialVersionUID = -3078188121739515720L;
	private static Set<String> allowed;

	static {
		allowed = new HashSet<String>();
		allowed.add("pl");
		allowed.add("en");
		allowed.add("de");
	}

	private Locale locale;

	@Inject
	private User user;

	// @Inject
	// private Event<LanguageChangeEvent> event;

	public Locale getLocale() {
		if (locale == null) {
			locale = prepareLocale(null);
		}
		user.setLocale(locale);
		return locale;
	}

	public String getLanguage() {
		return getLocale().getLanguage();
	}

	public void setLanguage(String language) {
		// String oldLanguage = locale.getLanguage();
		// locale = new Locale(language);
		// FacesContext.getCurrentInstance().getViewRoot().setLocale(locale);
		// user.setLocale(locale);
		// event.fire(new LanguageChangeEvent(language, oldLanguage));
		locale = prepareLocale(language);
	}

	private Locale prepareLocale(String language) {
		Locale locale = null;

		if (StringUtils.isNotBlank(language)) {
			locale = new Locale(language);
			log.info("language locale: {}", locale);
		} else {
			locale = FacesContext.getCurrentInstance().getExternalContext().getRequestLocale();
			log.info("request locale: {}", locale);
		}

		if (locale == null || locale.getLanguage() == null
				|| !allowed.contains(locale.getLanguage().toLowerCase())) {
			locale = Locale.getDefault();
			log.info("default locale: {}", locale);
		}
		return locale;
	}
}
